'use client';

import React, { useState } from 'react';
import { Modal, Upload, Button, message, Space, List } from 'antd';
import { UploadOutlined, DeleteOutlined } from '@ant-design/icons';
import type { UploadFile, UploadProps } from 'antd';

interface UploadDataModalProps {
  open?: boolean;
  onCancel?: () => void;
  onClose?: () => void;
  onSubmit?: (files: File[]) => Promise<void>;
  orderInfo?: {
    id: string;
    orderNumber: string;
    experimentName: string;
  };
}

const UploadDataModal: React.FC<UploadDataModalProps> = ({
  open = false,
  onCancel,
  onClose,
  onSubmit,
  orderInfo,
}) => {
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [uploading, setUploading] = useState(false);

  const handleUpload = async () => {
    if (fileList.length === 0) {
      message.warning('请选择要上传的文件');
      return;
    }

    setUploading(true);
    try {
      const files = fileList.map(file => file.originFileObj as File);
      
      if (onSubmit) {
        await onSubmit(files);
      } else {
        // TODO: 调用实际的上传API
        console.log('上传文件:', files);
        message.success('文件上传成功');
      }
      
      setFileList([]);
      onClose?.();
    } catch (error) {
      console.error('文件上传失败:', error);
      message.error('文件上传失败');
    } finally {
      setUploading(false);
    }
  };

  const handleCancel = () => {
    setFileList([]);
    onCancel?.();
    onClose?.();
  };

  const uploadProps: UploadProps = {
    name: 'file',
    multiple: true,
    fileList,
    beforeUpload: (file) => {
      // 检查文件类型和大小
      const isValidType = [
        'application/zip',
        'application/x-zip-compressed',
        'application/rar',
        'application/x-rar-compressed',
        'application/pdf',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'image/jpeg',
        'image/jpg',
        'image/png',
        'image/gif',
        'text/plain',
      ].includes(file.type);

      if (!isValidType) {
        message.error('只支持上传压缩包、图片、文档格式的文件');
        return false;
      }

      const isLt100M = file.size / 1024 / 1024 < 100;
      if (!isLt100M) {
        message.error('文件大小不能超过100MB');
        return false;
      }

      setFileList(prev => [...prev, file as UploadFile]);
      return false; // 阻止自动上传
    },
    onRemove: (file) => {
      setFileList(prev => prev.filter(item => item.uid !== file.uid));
    },
    showUploadList: false,
  };

  const getFileIcon = (file: UploadFile) => {
    const fileType = file.type || '';
    if (fileType.includes('image')) {
      return '🖼️';
    } else if (fileType.includes('zip') || fileType.includes('rar')) {
      return '📦';
    } else if (fileType.includes('pdf')) {
      return '📄';
    } else if (fileType.includes('word')) {
      return '📝';
    } else if (fileType.includes('excel')) {
      return '📊';
    }
    return '📁';
  };

  const formatFileSize = (size: number) => {
    if (size < 1024) return `${size}B`;
    if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)}KB`;
    return `${(size / (1024 * 1024)).toFixed(1)}MB`;
  };

  return (
    <Modal
      title="上传数据"
      open={open}
      onCancel={handleCancel}
      width={600}
      footer={[
        <Button key="cancel" onClick={handleCancel}>
          取消
        </Button>,
        <Button
          key="upload"
          type="primary"
          loading={uploading}
          onClick={handleUpload}
          disabled={fileList.length === 0}
          style={{ backgroundColor: '#69cac3', borderColor: '#69cac3' }}
        >
          确定上传
        </Button>,
      ]}
    >
      {orderInfo && (
        <div className="mb-4 p-3 bg-gray-50 rounded">
          <div><strong>订单编号:</strong> {orderInfo.orderNumber}</div>
          <div><strong>实验名称:</strong> {orderInfo.experimentName}</div>
        </div>
      )}

      <div className="mb-4">
        <Upload {...uploadProps}>
          <Button icon={<UploadOutlined />} style={{ borderColor: '#69cac3', color: '#69cac3' }}>
            选择文件
          </Button>
        </Upload>
        <div className="mt-2 text-sm text-gray-500">
          支持上传：压缩包(.zip, .rar)、图片(.jpg, .png, .gif)、文档(.pdf, .doc, .docx, .xls, .xlsx, .txt)
          <br />
          单个文件大小不超过100MB
        </div>
      </div>

      {fileList.length > 0 && (
        <div>
          <div className="mb-2 font-medium">已选择文件 ({fileList.length}个):</div>
          <List
            size="small"
            bordered
            dataSource={fileList}
            renderItem={(file) => (
              <List.Item
                actions={[
                  <Button
                    key="delete"
                    type="link"
                    size="small"
                    danger
                    icon={<DeleteOutlined />}
                    onClick={() => setFileList(prev => prev.filter(item => item.uid !== file.uid))}
                  >
                    删除
                  </Button>,
                ]}
              >
                <Space>
                  <span style={{ fontSize: '16px' }}>{getFileIcon(file)}</span>
                  <div>
                    <div className="font-medium">{file.name}</div>
                    <div className="text-sm text-gray-500">
                      {formatFileSize(file.size || 0)}
                    </div>
                  </div>
                </Space>
              </List.Item>
            )}
          />
        </div>
      )}
    </Modal>
  );
};

export default UploadDataModal; 